#ifndef CONNECTION_H
#define CONNECTION_H

#include <QtSql>
#include <QDebug>
#include "qdom.h"
#include <QFile>
#include <QtXml>
#include <QDomNode>
#include <QCoreApplication>

static bool createConnection()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("120.78.130.120");
    db.setDatabaseName("car_manager");
    db.setUserName("root");
    db.setPassword("778855");
    if(!db.open())
    {
        return false;
    }
    else
    {
        qDebug()<<"db open is ok!";
    }
    //创建厂家表和品牌表
    QSqlQuery query;
    query.exec("create table factory(id varchar(10) , name varchar(10), primary key (id))");
    query.exec(QString("insert into factory values('0','请选择厂家')"));
    query.exec(QString("insert into factory values('01','一汽大众')"));
    query.exec(QString("insert into factory values('02','二汽神龙')"));
    query.exec(QString("insert into factory values('03','上海大众')"));

    query.exec("create table brand(id varchar(10), name varchar(10), factory varchar(10), price int, sum int, sell int, last int, primary key(id))");
    query.exec(QString("insert into brand values('01','奥迪A6','一汽大众',36,50,10,40)"));
    query.exec(QString("insert into brand values('02','捷达','一汽大众',34,20,5,15)"));
    query.exec(QString("insert into brand values('03','宝来','一汽大众',41,80,20,60)"));
    query.exec(QString("insert into brand values('04','奔驰','一汽大众',83,40,15,25)"));
    query.exec(QString("insert into brand values('05',毕加索,'二汽神龙',39,50,15,35)"));
    query.exec(QString("insert into brand values('06','富康','二汽神龙',28,60,10,50)"));
    query.exec(QString("insert into brand values('07','标致307','二汽神龙',27,70,20,50)"));
    query.exec(QString("insert into brand values('08','桑塔纳','上海大众',25,75,25,50)"));
    query.exec(QString("insert into brand values('09','帕萨特','上海大众',27,65,20,45)"));

    //创建密码表
    query.exec("create table password(pwd varchar(16), primary key (pwd))");
    query.exec(QString("insert into password values('0a0a0a0a0')"));
    return true;
}
//创建XML文件
static bool createXml()
{
    QFile file("data.xml");
    if(file.exists())
        return true;
    if(!file.open(QIODevice::WriteOnly |QIODevice::Truncate))//(该设备是开放式的。请注意，这种模式意味着截断。如果可能的话，设备在打开之前被截断。设备的所有早期内容都丢失了。)//可以用QIODevice，Truncate表示清空原来的内容
        return false;
    QDomDocument doc;
        //写入xml头部
    QDomProcessingInstruction instruction;//添加处理命令
    instruction = doc.createProcessingInstruction("xml","version = \"1.0\" encoding=\"UTF-8\" ");
    doc.appendChild(instruction);
        //添加根节点
    QDomElement root = doc.createElement(QString("日常销售清单"));//.创建根节点
    doc.appendChild(root);
        //添加第一个子节点及其子元素
        //输出到文件
    QTextStream out(&file);
    doc.save(out,4);//缩进4格
    file.close();
    return true;
}

#endif // CONNECTION_H
